<?php

/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/3/16
 * Time: 13:40
 */
namespace app\bbs\api;

use app\bbs\model\ForumAdmingroup;
use app\bbs\model\ForumPost;
use app\bbs\model\ForumPostcomment;
use app\common\api\BaseApi;
use app\system\api\MemberApi;
use app\system\api\BabyApi;
use app\bbs\api\BbsMemberApi;

class ForumPostApi extends BaseApi{

    /**
     * 添加
     */
    const ADD = "bbs/ForumPostApi/add";
    /**
     * 保存
     */
    const SAVE = "bbs/ForumPostApi/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "bbs/ForumPostApi/saveByID";

    /**
     * 删除
     */
    const DELETE = "bbs/ForumPostApi/delete";

    /**
     * 查询
     */
    const QUERY = "bbs/ForumPostApi/query";
    /**
     * 查询一条数据
     */
    const GET_INFO = "bbs/ForumPostApi/getInfo";
    const SET_INC  = "bbs/ForumPostApi/setInc";
    const SET_DEC  = "bbs/ForumPostApi/setDec";

    const QUERY_WITH_COUNT   = "bbs/ForumPostApi/queryWithCount";
    const QUERY_WITH_THREAD  = "bbs/ForumPostApi/queryWithThread";
    const QUERY_WITH_COMMENT = "bbs/ForumPostApi/queryWithComment";

    /**
     * 帖子查询
     */
    const QUERY_POST = "bbs/ForumPostApi/queryPost";

    /**
     * 帖子详情
     */
    const DETAIL_POST = "bbs/ForumPostApi/detailPost";

    /**
     * 评论查询
     */
    const QUERY_COMMENT = "bbs/ForumPostApi/commentQuery";

    /**
     * 主题回帖
     */
    const REPLY    = "bbs/ForumPostApi/reply";
    const QUERY_NO_PAGE = "bbs/ForumThreadApi/queryNoPaging";
    /**
     * 我的回复
     */
    const MY_REPLY = "bbs/ForumPostApi/queryByUid";
    /**
     * 回复我的
     */
    const REPLY_ME = "bbs/ForumPostApi/replyByUid";
    /**
     * 评论我的
     */
    const COMMENT_ME = "bbs/ForumPostApi/commentByUid";
    /**
     * 删除帖子
     */
    const DELETE_POST = "bbs/ForumPostApi/deletePost";
    /**
     * 删除评论
     */
    const DELETE_COMMENT = "bbs/ForumPostApi/deleteComment";
    /**
     * 帖子评论
     */
    const REPLY_POST = "bbs/ForumPostApi/replyPost";

    protected function _init(){
        $this -> model = new ForumPost();
    }

    //评论我的
    public function commentByUid($uid,$page=1,$size=10,$order='id desc'){
        // $where = '`author_id`=\''.$uid.'\' and `status`>=0';

        // $result = $this->queryNoPaging($where,false,'pid');
        // if(!$result['status']) return $this->apiReturnErr('服务器故障：post page');
        // $ids    = $this->getIds($result['info'],',','pid');
        // if($ids){
            $model = new ForumPostcomment();
            // $where = ' `pid` in ('.$ids.')';
            $where = ' `to_uid` = '.$uid;
            $page  = intval($page)>1 ?intval($page):1;
            $start = ($page-1)*$size;
            $count = $model-> field('id')->where($where)->count();
            $list  = $model-> where($where)->limit($start,$size)->order($order)->select();
            if(false === $list) $this->apiReturnErr($model->getDbError());
            $count = $model->where($where)->count();
            if(false === $count) $this->apiReturnErr($model->getDbError());
        // }else{
        // $count=0;$list=[];
        // }
        return $this->apiReturnSuc(['count'=>$count,'list'=>$list]);
    }
    //回复我的
    public function replyByUid($uid,$page=1,$size=10,$order='dateline desc'){
        $where = '`author_id`=\''.$uid.'\' and `status`>=0';

        $result = apiCall(ForumThreadApi::QUERY_NO_PAGE,[$where,false,'tid']);
        if(!$result['status']) return $this->apiReturnErr('服务器故障：thread page');
        $ids    = $this->getIds($result['info'], ',','tid');
        if($ids){
            $model = $this->model;
            $where = ' `status`>=0 and `tid` in ('.$ids.')';
            $page  = intval($page)>1 ?intval($page):1;
            $start = ($page-1)*$size;
            $count = $model->field('tid')->where($where)->count();
            $list  = $model->where($where)->limit($start,$size)->order($order)->select();
        }else{
            $count = 0;$list = [];
        }
        return $this->apiReturnSuc(['count'=>$count,'list'=>$list]);
    }
    //我的回复
    public function queryByUid($uid,$page=1,$size=10,$order='id desc'){
        $where = '`author_id`=\''.$uid.'\' and status>=0';
        $page  = intval($page)>1 ?intval($page):1;
        $start = ($page-1)*$size;
        $model = $this->model;
        $count = $model->field('tid')->where($where)->count();
        $list  = $model->where($where)->limit($start,$size)->order($order)->select();
        return $this->apiReturnSuc(['count'=>$count,'list'=>$list]);
    }
    //评论回复同级查询
    public function queryWithComment($map = null, $page = array('curpage'=>0,'size'=>10), $order = false){

        $query = $this -> model;
        $query = $query -> field('author_id,dateline,message,0 as to_uid');
        if(!empty($map)){
            $query = $query -> where($map);
            if(isset($map['tid'])){
                $query = $query -> union('select author_id,dateline,comment as message,to_uid from itboye_forum_postcomment where tid='.$map['tid'],true);
            }else{
                return $this->apiReturnErr('需要配置tid');
            }

        }
        if(false !== $order)  $query = $query -> order($order);
        $query = $query -> page($page['curpage'] . ',' . $page['size']);
        $list = $query -> select();
        if (false === $list) return $this -> apiReturnErr($this -> model -> getDbError());

        $count = 120;//$this -> model -> alias('p') -> join("itboye_forum_thread t on p.tid=t.tid","left") -> where($map) -> count();
        return $this -> apiReturnSuc(["count" => $count, "list" => $list]);
    }

    public function queryWithThread($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){
        $query = $this -> model->alias('p')-> join("itboye_forum_thread t on p.tid=t.tid","left");

        $query = $query -> page($page['curpage'] . ',' . $page['size']);

        if(!is_null($map))    $query = $query -> where($map);
        if(false !== $order)  $query = $query->order($order);
        if(false !== $fields) $query = $query->field($fields);
        $list = $query -> select();
        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model ->alias('p')-> join("itboye_forum_thread t on p.tid=t.tid","left") -> where($map) -> count();
        // 查询满足要求的总记录数
        // $Page = new \Think\Page($count, $page['size']);

        // //分页跳转的时候保证查询条件
        // if ($params !== false) {
        //     foreach ($params as $key => $val) {
        //         $Page -> parameter[$key] = urlencode($val);
        //     }
        // }

        // // 实例化分页类 传入总记录数和每页显示的记录数
        // $show = $Page -> show();

        return $this -> apiReturnSuc(["count" => $count, "list" => $list]);

    }


    /**
     * 回复分页查询
     * @param $fid
     * @param $tid
     * @param $typeid - unuse
     * @param $curpage
     * @param $pagesize
     * @param $maxcomment
     * @param $view_inc
     * @param $all
     * @return array
     */
    public function queryPost($fid,$tid,$curpage,$pagesize,$maxcomment,$view_inc,$all=false,$commentorder='dateline asc'){
        $curpage    = intval($curpage);
        $pagesize   = intval($pagesize);
        $maxcomment = intval($maxcomment);

        if($curpage < 1)    $curpage = 1;
        // if($pagesize > 30) $pagesize = 30;
        if($pagesize < 0)   $pagesize = 10;
        if($maxcomment < 0) $maxcomment = 2;
        // if($maxcomment>10) $maxcomment = 10;
        // if(in_array($tid,array('rrasj','fxphb')))
        //     $fid = 0;

        $map = [
            'fid'    => $fid,
            'tid'    => $tid,
            // 'typeid' => $typeid,
            // 'status' => 1, 审核, 0 正常 -1 删除
        ];
        $page = ['curpage'=>$curpage,'size'=>$pagesize];
        if(!$all) $map['status'] = 0;
        if(0 === $pagesize){
            return $this->apiReturnSuc([]);
        }else{
            // $result = apiCall(ForumPostApi::QUERY_WITH_COUNT,[$map,$page,$order]);
            $result = $this->queryWithCount($map,$page,'position asc');
            // trace('---result---');
            // trace($result);
            if($result['status']){
                $info = $result['info'];
                if(!empty($info['list'])){
                    foreach($info['list'] as &$val){
                        //时间转换
                        $val['dateline_show'] = date("Y-m-d H:i:s",$val['dateline']);
                        //作者宝宝信息
                        $val['baby_default']  = apiCall(BabyApi::GET_DEFAULT,[$val['author_id']]);
                        //查询用户头像
                        // $this->getUserInfo($val['author_id'],$val);
                        $userInfo = $this->getUserInfo($val['author_id']);
                        $val['head']   =  empty($userInfo) ? '' : $userInfo['head'];
                        $val['author'] =  empty($userInfo) ? '' : $userInfo['nickname'];
                        $val['sex']    =  empty($userInfo) ? '' : $userInfo['sex'];
                        unset($userInfo);
                        //查询附件
                        $this->queryAttachment($tid,$val['pid'],$val);

                        //查询评论
                        $this->queryComments($tid,$val['pid'],$maxcomment,$val,$commentorder);

                    }

                }
                //查看次数加1
                if($view_inc==1){
                    $map = array(
                        'tid' => $tid
                    );
                    apiCall(ForumThreadApi::SET_INC,array($map,'views'));
                }
                return $this->apiReturnSuc($info);
            }else{
                return $this->apiReturnErr('查询失败');
            }
        }
    }

    /**
     * 回复详情
     * @param $fid
     * @param $tid
     * @param $pid
     */
    public function detailPost($fid,$tid,$pid){
        $map = array(
            'fid' => $fid,
            'tid' => $tid,
            'pid' => $pid
        );
        $result = apiCall(ForumPostApi::GET_INFO,array($map));
        // trace('=== detailPost');
        // trace($result);
        if($result['status']){
            if(empty($result['info'])) return $this->apiReturnSuc($result['info']);
            $info = $result['info'];
            $map = array(
                'pid' => $pid,
                'tid' => $tid
            );
            $result = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map,false,array('aid')));
            // trace($result);
            if($result['status']){
                //时间转换
                $info['dateline_show'] = date("Y-m-d H:i:s",$info['dateline']);
                //作者宝宝信息
                $info['baby_default']  = apiCall(BabyApi::GET_DEFAULT,[$info['author_id']]);
                //查询用户信息
                // $this->getUserInfo($info['author_id'],$info);
                $userInfo = $this->getUserInfo($info['author_id']);
                $info['head']   =  empty($userInfo) ? '' : $userInfo['head'];
                $info['author'] =  empty($userInfo) ? '' : $userInfo['nickname'];
                $info['sex']    =  empty($userInfo) ? '' : $userInfo['sex'];
                unset($userInfo);
                //查询附件
                $this->queryAttachment($fid,$tid,$info);
                //查询评论
                $this->queryComments($tid,$info['pid'],2,$info);
            }

            return $this->apiReturnSuc($info);
        }else{
            return $this->apiReturnErr('查询失败');
        }
    }

    /**
     * 评论查询
     * @param $tid
     * @param $pid
     * @param $curpage
     * @param $pagesize
     * @param $curpage
     * @param $pagesize
     * @return array
     */
    public function commentQuery($tid,$pid,$curpage,$pagesize){

        $curpage  = intval($curpage);
        $pagesize = intval($pagesize);

        if($curpage < 1) $curpage = 1;
        // if($pagesize > 30) $pagesize = 30;
        if($pagesize <= 0) $pagesize = 10;
        $map = [
            'tid' => $tid,
            'pid' => $pid
        ];

        $page = ['curpage'=>$curpage,'size'=>$pagesize];
        $order['id'] = 'asc';

        $result = apiCall(ForumPostcommentApi::QUERY_WITH_COUNT,array($map,$page,$order));

        if($result['status']){
            foreach($result['info']['list'] as &$val){
                //时间转换
                $val['dateline_show'] = date("Y-m-d H:i:s",$val['dateline']);
                //查询用户信息
                // $this->getUserInfo($val['author_id'],$val);
                $userInfo = $this->getUserInfo($val['author_id']);
                $val['head']   =  empty($userInfo) ? '' : $userInfo['head'];
                $val['author'] =  empty($userInfo) ? '' : $userInfo['nickname'];
                $val['sex']    =  empty($userInfo) ? '' : $userInfo['sex'];
                if($val['author_id'] != $val['to_uid']) $userInfo = $this->getUserInfo($val['to_uid']);
                $val['to_uinfo']['head']     =  empty($userInfo) ? '' : $userInfo['head'];
                $val['to_uinfo']['sex']      =  empty($userInfo) ? '' : $userInfo['sex'];
                $val['to_uinfo']['nickname'] =  empty($userInfo) ? '' : $userInfo['nickname'];
                $val['to_uinfo']['realname'] =  empty($userInfo) ? '' : $userInfo['realname'];
                unset($userInfo);
            }

            return $this->apiReturnSuc($result['info']);
        }else{
            return $this->apiReturnErr('查询失败');
        }

    }
    //帖子回复
    public function reply($fid,$tid,$author_id,$message,$attachments){
        $result = apiCall(ForumThreadApi::GET_INFO,[['tid'=>$tid,'fid'=>$fid]]);
        if(!$result['status']) return $this->apiReturnSuc('服务器故障： thread get');
        if(empty($result['info'])) return $this->apiReturnSuc('无此帖');
        if(1 == $result['info']['status']) return $this->apiReturnSuc('该帖审核中');
        $subject = $result['info']['subject'];
        $useip   = get_client_ip(1);
        //验证用户权限
        // $result = apiCall(ForumUserAdmingroupApi::POWER,array($author_id));
        // if($result['status']){
        //     $power = $result['info'];
        //     if(is_array($power)){
        //         if($power[ForumAdmingroup::ALLOW_POST] == 0 && ($power['fid'] == $fid || $power['fid'] == 0)){
        //             return $this -> apiReturnErr("无回帖权限");
        //         }
        //     }
        // }else{
        //     return $this -> apiReturnErr($result['info']);
        // }

        //查询帖子楼层
        $map = [
            'tid' => $tid,
            'fid' => $fid
        ];
        $order['pid'] = 'desc';
        $model = new ForumPost();
        $result = $model->where($map)->order($order)->lock(true)->find();
        $position = 0;
        if(false === $result) return $this->apiReturnErr('回帖失败');
        if($message == $result['message'])  return $this->apiReturnErr('重复回帖');
        $position = $result['position'] + 1;
        //帖子回复数+1
        apiCall(ForumThreadApi::SET_INC,[['tid' => $tid],'replies']);
        //论坛回复数+1
        $result = apiCall("bbs/ForumForumApi/setInc",[['fid' => $fid],'posts']);

        $entity = [
            // 'author'    => $author,
            'author_id' => $author_id,
            'subject'   => $subject,
            'dateline'  => time(),
            'message'   => $message,
            'useip'     => $useip,
            // 'invisible' => 0,//unuse
            'status'    => 0,   //0正常，1审核，-1删除
            'comment'   => 0,
            'position'  => $position,
            'tid'       => $tid,
            'likes'     =>0,
            'fid'       => $fid
        ];

        $result = $model->lock(false)->add($entity);
        $pid    = $result;

        if($result!==false){

            //添加附件
            if($attachments !== ""){
                $aid = explode(',',$attachments);
                $dataList = array();
                $i = 0;
                if(count($aid) >6){
                    $aid = array_slice($aid,0,6);
                }
                foreach($aid as $v){
                    $dataList[$i] = array(
                        'tid' => $tid,
                        'pid' => $pid,
                        'uid' => $author_id,
                        'aid' => $v,
                    );
                    $i++;
                }
                $result = apiCall(ForumAttachmentApi::ADD_ALL,array($dataList));
                if(!$result['status']) return $this -> apiReturnErr($result['info']);
            }
            return $this->apiReturnSuc($pid);
        }else{
            return $this->apiReturnErr('回帖失败');
        }
    }


    /**
     * 删除回复
     * @param $uid
     * @param $fid
     * @param $tid
     * @param $pid
     * @return array
     */
    public function deletePost($uid,$fid,$tid,$pid){

        $map = [
            'fid' => $fid,
            'tid' => $tid,
            'pid' => $pid
        ];
        $result = apiCall(ForumPostApi::GET_INFO,[$map]);
        //查询该帖子
        if($result['status']){
            if(empty($result['info'])){
                return $this->apiReturnErr('指定回复不存在');
            }else{
                $post_info = $result['info'];
                if($post_info['status']==-1){
                   return $this->apiReturnErr('指定回复已删除');
                }
            }
        }else{
            return $this->apiReturnErr('删除失败');
        }

        $model = new \think\model\Adv();
        $model->startTrans();
        if($post_info['author_id']==$uid){
            //作者可以删除自己的帖子
            $result = apiCall(ForumPostApi::SAVE,[$map,['status'=>-1]]);
        }else{
            //判断是否有管理员的删帖权限 并删帖
            $result = apiCall(ForumUserAdmingroupApi::DELETE_POST,[$uid,$fid,$tid,$pid]);
        }
        if($result['status']){
            //帖子回复数-1
            $map = ['tid' => $tid];
            $result = apiCall(ForumThreadApi::SET_DEC,[$map,'replies',1]);
            //论坛回复数-1
            $map = ['fid' => $fid];
            $result = apiCall("bbs/ForumForumApi/setDec",[$map,'posts',1]);
            $model ->commit();
            return $this->apiReturnSuc('删除成功');
        }else{
            $model ->rollback();
            return $this->apiReturnErr('删除失败');
        }

    }


    public function deleteComment($uid,$tid,$pid,$id){

        // 获取帖子信息，帖子主人以及评论者可删除
        $map = array(
            'tid' => $tid,
            'pid' => $pid
        );

        $result = apiCall(ForumPostApi::GET_INFO,array($map));

        if($result['status']){
            if(empty($result['info'])){
                return $this->apiReturnErr('指定评论不存在');
            }
        }else{
            return $this->apiReturnErr('删除失败');
        }


        $can_delete= false;
        $post_info = $result['info'];
        $fid       = $post_info['fid'];

        //查询评论信息
        $map = array(
            'tid' => $tid,
            'pid' => $pid,
            'id'  => $id
        );
        $result = apiCall(ForumPostcommentApi::GET_INFO,array($map));
        if($result['status']) {
            $comment_info = $result['info'];
        }else{
            return $this->apiReturnErr('删除失败');
        }
        if(empty($comment_info)){
            return $this->apiReturnErr('删除失败,指定评论不存在');
        }

        if($post_info['author_id']==$uid){
            //帖子主人可以删
            $can_delete = true;
        }else{
            if($comment_info['author_id']==$uid){
                //评论者可删除
                $can_delete = true;
            }
        }

        //验证用户权限
        $result = apiCall(ForumUserAdmingroupApi::POWER,array($uid));
        if($result['status']){
            $power = $result['info'];

            if(is_array($power)){
                if($power[ForumAdmingroup::ALLOW_DEL_POST] == 1 && ($power['fid'] == $fid || $power['fid'] == 0)){
                    $can_delete = true;
                }

            }
        }else{
            return $this -> apiReturnErr($result['info']);
        }


        if(!$can_delete){
            return $this->apiReturnErr('该用户没有删帖权限');
        }


        $map = array(
            'tid' => $tid,
            'pid' => $pid,
            'id' => $id
        );

        $result = apiCall(ForumPostcommentApi::DELETE,array($map));

        if($result['status']){

            if($result['info']<1){
                return $this->apiReturnErr('删除失败');
            }else{

                //统计帖子评论数量，为0需要设置
                $map = array(
                    'tid' => $tid,
                    'pid' => $pid,
                );
                $result = apiCall(ForumPostcommentApi::COUNT,array($map));
                if($result['status']){
                    if(!empty($result['info']) && $result['info'] == 0){
                        //帖子是否评论为0
                        $map = array(
                            'pid' => $pid,
                            'tid' => $tid
                        );
                        $result = apiCall(ForumPostApi::SAVE,array($map,array('comment'=>0)));
                    }
                }

                return $this->apiReturnSuc('删除成功');
            }

        }else{
            return $this->apiReturnErr('删除失败');
        }
    }

    public function replyPost($pid,$tid,$author_id,$comment,$to_uid){

        //信息验证
        $result = apiCall(ForumThreadApi::GET_INFO,[['tid' => $tid]]);
        if(!$result['status']) return $this -> apiReturnErr('服务器故障：thread get ');
        if(empty($result['info'])) return $this -> apiReturnErr('无此帖');
        $fid = $result['info']['fid'];
        // $result = apiCall(ForumPostApi::GET_INFO,[['tid' => $tid,'pid'=>$pid]]);
        // if(!$result['status']) return $this -> apiReturnErr('服务器故障：post get ');
        // if(empty($result['info'])) return $this -> apiReturnErr('无此回复');

        $useip  = get_client_ip(1);
        $entity = [
            'tid'       => $tid,
            'pid'       => $pid,
            'fid'       => $fid,
            // 'author'    => $author,
            'author_id' => $author_id,
            'dateline'  => time(),
            'comment'   => $comment,
            'useip'     => $useip,
            'rpid'      => 0,
            'to_uid'    => $to_uid,
        ];

        $result = apiCall(ForumPostcommentApi::ADD,[$entity]);
        if($result['status']){
            if($result['info']>0 && $pid){
                //回复有评论了
                $map = [
                    'pid' => $pid,
                    'tid' => $tid
                ];
                 $r = apiCall(ForumPostApi::SAVE,array($map,array('comment'=>1)));
                // $r = $this->setInc($map,'comment');
                if(!$r['status'])  return $this -> apiReturnErr('服务器故障：post comment inc');
            }
            $id = $result['info'];
            // else{
            //     return $this->apiReturnErr('评论失败');
            // }
            return $this->apiReturnSuc(['msg'=>'评论成功','id'=>$id]);
        }else{
            return $this->apiReturnErr('评论失败');
        }
    }

    /**
     * 查询用户主体信息
     */
    private function getUserInfo($uid){
        $result = apiCall(MemberApi::GET_INFO,[['uid'=>$uid]]);
        if($result['status'] && $result['info']){
            return $result['info'];
        }else{
            return [];//$this->apiReturnErr('查询用户信息失败');
        }
    }
    /**
     * 查询用户头像
     */
    private function getUserHeadByID($uid){
        $result = apiCall(BbsMemberApi::GET_USER_INFO,[$uid,false,false,false,false]);
        if($result['status'] && $result['info']){
            return $result['info']['head'];
        }else{
            return '0';//$this->apiReturnErr('查询用户信息失败');
        }
    }

    /**
     * 查询附件
     */
    private function queryAttachment($tid,$pid,&$arr){

        //查询附件
        $map = array(
            'pid' => $pid,
            'tid' => $tid
        );
        $result = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map,false,array('aid')));
        if($result['status']){
            $arr['img'] = array();
            foreach($result['info'] as $key=>$v){
                if($key >5)break;
                array_push($arr['img'],$v['aid']);
            }

        }

    }

    /**
     * 查询指定条数评论
     */
    private function queryComments($tid,$pid,$maxcomment=2,&$arr,$order='dateline asc'){
       // trace('=== queryComments');
       $maxcomment = intval($maxcomment);
       if($maxcomment<0) $maxcomment = 2;
       if($arr['comment']){
            $arr['view_more'] = 0;
            $map = [
                'tid' => $tid,
                'pid' => $pid,
            ];
            // $order['id'] = 'desc';
            if(0 >= $maxcomment){
                $result = apiCall(ForumPostcommentApi::COUNT,[$map]);
                if(!$result['status']) return $this->apiReturnErr($result['info']);
                $count = intval($result['info']);
                if($count>$maxcomment){
                        $arr['view_more'] = 1;
                    }
                $arr['comment_num'] = $count;
                $arr['comments']    = [];
            }else{
                $page   = array('curpage'=>0,'size'=>$maxcomment);
                $result = apiCall(ForumPostcommentApi::QUERY_WITH_COUNT,array($map,$page,$order));
                // trace($result);
                if($result['status']){
                    if($result['info']['count']>$maxcomment){
                        $arr['view_more'] = 1;
                    }
                    $arr['comment_num'] = $result['info']['count'];
                    $arr['comments']    = $result['info']['list'];

                    foreach($arr['comments'] as &$val){
                        //时间转换
                        $val['dateline_show'] = date("Y-m-d H:i:s",$val['dateline']);
                        //查询用户
                        $userInfo = $this->getUserInfo($val['author_id']);
                        $val['head']   =  empty($userInfo) ? '' : $userInfo['head'];
                        $val['author'] =  empty($userInfo) ? '' : $userInfo['nickname'];
                        $val['sex']    =  empty($userInfo) ? '' : $userInfo['sex'];
                        if($val['author_id'] != $val['to_uid']){
                            $userInfo = $this->getUserInfo($val['to_uid']);
                        }
                        $val['to_uinfo']['head']   =  empty($userInfo) ? '' : $userInfo['head'];
                        $val['to_uinfo']['sex']    =  empty($userInfo) ? '' : $userInfo['sex'];
                        $val['to_uinfo']['nickname'] =  empty($userInfo) ? '' : $userInfo['nickname'];
                        $val['to_uinfo']['realname'] =  empty($userInfo) ? '' : $userInfo['realname'];
                        unset($userInfo);
                    }
                }else{
                    return $this->apiReturnErr('获取'.$arr['pid'].'评论失败');
                }
            }
        }

    }


    /**
     * 查看所有帖子，根据显示未显示分
     */
    public function queryAllPost($map = null, $display = 1, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){

        $query = $this->model;
        $join = array('LEFT JOIN __FORUM_FORUM__ ON __FORUM_POST__.fid=__FORUM_FORUM__.fid');
        $query = $query->join($join);
        $where = array();
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if($display == 1){
            $where['_complex'] = array(
                'invisible' => 1,
                'modnewposts' => 0,
                '_logic' => 'or'
            );
        }else{
            $where['_complex'] = array(
                'invisible' => 0,
                'modnewposts' => 1,
            );
        }
        $query = $query->where($where);

        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> join($join) -> where($map) -> where($where)-> count();
        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));

    }

    private function getIds($arr,$dif='',$field='id'){
        $str = '';
        foreach ($arr as $v) {
            $str .= ($str ? $dif : '').$v[$field];
        }
        return $str;
    }
}